import { Middleware } from "koa";
import { RuntimeError } from "../model/RuntimeErrorr";
import { Result } from "../factory/Result";
import { logger } from "../log";

export function errorHandler(): Middleware {
  return async (ctx, next) => {
    try {
      await next();
    } catch (e) {
      if (e instanceof RuntimeError) {
        ctx.body = Result.fail(e.message);
      } else {
        logger.error(e);
        ctx.body = Result.fail((e as any)?.message || "未知错误");
      }
    }
  };
}
